import router from 'next/router';
import { ReactNode, useState } from 'react';
import { Form, message, Modal } from 'antd';
import Button from './button';

export default function AddButton({ children, dlgtitle, onSave }: { children: ReactNode; dlgtitle: string; onSave(): Promise<true | string>; }) {
	const [visible, setvisible] = useState(false);
	const [confirmLoading, setConfirmLoading] = useState(false);
	return <>
		<div className='e'>
			<Button value='新增' onClick={() => {
				setvisible(true);
			}} />
		</div>
		<Modal
			confirmLoading={confirmLoading}
			title={dlgtitle || '新增'}
			visible={visible}
			onCancel={() => {
				if (confirmLoading) {
					return;
				}
				setConfirmLoading(false);
				setvisible(false);
			}}
			footer={null}
		>
			<Form layout='horizontal'>{children}
				<div className='footer'>
					<Button value='保存' onClick={async () => {
						if (confirmLoading) {
							return;
						}
						setConfirmLoading(true);
						try {
							const data = await onSave();
							if (data === true) {
								message.success({ content: '保存成功' });
								router.reload();
							} else {
								message.error({ content: data });
							}
						} catch (error) {
							console.error(error);
						} finally {
							setConfirmLoading(false);
						}
					}} />
				</div>
			</Form>
		</Modal>
		<style jsx>{`
.footer{
	display: flex;
	justify-content: center;
}
.e{
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin: 0.5rem 0;
}
`}</style>
	</>;
}
